<template>
  <div class="markedEdit" @click.stop="aotuTab=false">
    <div>
      <jc-button
        :btn-arr="['remove', 'pass', 'sub', 'save', 'reload', 'option', 'list']"
        :disab-arr="[isDisabled && 'save', 'close', 'cancel', 'toExcel', 'chart', 'com1', 'com2', 'freeze']"
        :list="'/marketPriceList'"
        @refresh="queryTSalOrderNtry"
        @save="subMarker('A')"
        @submit="subMarker('B')"
        @noSubmit="againReviewPrice"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @forbidden="forbidden(1)"
        @startUsing="forbidden(2)"
        @del="delectHandle"
      />
    </div>
    <el-tabs @tab-click="handleOther">
      <el-tab-pane :label="$t('market.priceDetail')">
        <div class="header-card">
          <div class="organization">
            <el-form :model="organizationValue" label-width="100px">
              <el-form-item :label="$t('market.state')">
                <el-tag :type="organizationValue.stateColor">
                  {{ organizationValue.fdocumentStatus }}
                </el-tag>
              </el-form-item>
              <el-form-item :label="$t('shop.fnumber')">
                <el-input v-model="organizationValue.fnumber" disabled size="mini" />
              </el-form-item>
              <el-form-item :label="$t('market.orderDate')">
                <el-date-picker
                  v-model.trim="organizationValue.fdate"
                  type="date"
                  size="mini"
                  style="width: 152px"
                  :disabled="isDisabled"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
              <el-form-item :label="$t('market.priceListName')">
                <el-input
                  v-model="organizationValue.fname"
                  :disabled="isDisabled"
                  size="mini"
                />
              </el-form-item>
              <el-form-item :label="$t('market.cust')">
                <el-autocomplete
                  v-model.trim="organizationValue.fcustName"
                  popper-class="my-autocomplete"
                  :fetch-suggestions="querySearch"
                  :disabled="isDisabled"
                  size="mini"
                  @focus="queryTBdCustomerList"
                  @select="clientData"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="clientVisiblit=true"
                  />
                  <template slot-scope="{ item }">
                    <div class="name">{{ item.fname }}</div>
                  </template>
                </el-autocomplete>
              </el-form-item>
              <el-form-item :label="$t('market.currency2')">
                <el-autocomplete
                  v-model.trim="organizationValue.fcurrency"
                  popper-class="my-autocomplete"
                  :fetch-suggestions="querySearch5"
                  size="mini"
                  :disabled="isDisabled"
                  @focus="queryTBdCurrency"
                  @select="currencyData"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="currencyVisiblit=true"
                  />
                  <template slot-scope="{ item }">
                    <div class="name">{{ item.fname }}</div>
                  </template>
                </el-autocomplete>
              </el-form-item>
              <el-form-item :label="$t('market.note')" style="width: 33%">
                <el-input
                  v-model="organizationValue.fnote"
                  :disabled="isDisabled"
                  size="mini"
                />
              </el-form-item>
              <el-form-item v-if="false" :label="$t('market.tax')">
                <el-checkbox v-model="organizationValue.fisIncludedTax" />
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="table-content">
          <el-button
            size="mini"
            :disabled="isDisabled"
            @click="newHang"
          >{{ $t('btn.newHang') }}<!--新增行--></el-button>
          <el-button size="mini" :disabled="isDisabled" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
          <el-button :disabled="isDisabled" size="mini" @click="batchFill">{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
        </div>
        <div>
          <jc-table
            :table-data="tableData"
            :table-header="tableHeader"
            serial
            :table-height="tableHeight"
            @rowClick="rowClick"
            @cellClick="cellClick"
          >
            <el-table-column :label="$t('market.fmaterial')" prop="fmaterialId" align="center" width="150px">
              <template slot-scope="scope">
                <el-input
                  v-model.trim="scope.row.fnumber"
                  :disabled="isDisabled"
                  size="mini"
                  @input="getAtuo(scope.$index, scope.row.fnumber)"
                >
                  <i slot="prefix" class="iconfont icon-jin-rud-ao-bo" @click="sonJumpMateriel(scope.row.fnumber)" />
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="handleGetMateriel(scope.row, scope.$index)"
                  />
                </el-input>
                <div v-if="aotuTab && tableIndex === scope.$index" :class="tableIndex<6 ? 'tabPosit': 'tabPosit1'">
                  <number-code :fnumber="fnumber" @material="materielSelectRow" />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.fmodel')" prop="fmodel" align="center" :show-overflow-tooltip="true" />
            <el-table-column :label="$t('shop.fspecificaTion')" prop="fspecificaTion" align="center" :show-overflow-tooltip="true" />
            <el-table-column :label="$t('market.fdescripTion')" prop="fdescripTion" align="center" min-width="200px" :show-overflow-tooltip="true" />
            <el-table-column :label="$t('market.saleUnit')" prop="funit" align="center" />
            <el-table-column :label="$t('market.priceCoeff')" prop="fpriceBase" align="center">
              <template slot-scope="scope">
                <el-input-number
                  v-model.number="scope.row.fpriceBase"
                  :disabled="isDisabled"
                  size="mini"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('shop.price')" prop="fprice" align="center">
              <template slot-scope="scope">
                <el-input-number
                  v-model.trim="scope.row.fprice"
                  :disabled="isDisabled"
                  size="mini"
                  :precision="4"
                  @change="priceHandel(scope.row.fprice, scope.$index)"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.lowestPrice')" prop="fdownPrice" align="center" width="80">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.fdownPrice"
                  size="mini"
                  :disabled="isDisabled"
                  :precision="4"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.effectiveDate')" prop="feffectivedate" align="center">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.feffectivedate"
                  value-format="yyyy-MM-dd"
                  style="width: 130px"
                  size="mini"
                  :disabled="isDisabled"
                  type="date"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.expiryDate')" prop="fexpriydate" align="center">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.fexpriydate"
                  value-format="yyyy-MM-dd"
                  style="width: 130px"
                  size="mini"
                  :disabled="isDisabled"
                  type="date"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.handle')" width="80px" align="center" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  size="mini"
                  :disabled="isDisabled"
                  @click="delectSale(scope.$index)"
                >{{ $t('shop.delete') }}</el-button>
              </template>
            </el-table-column>
          </jc-table>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.other')" name="log">
        <jc-marker
          ref="log"
          :fnumber="organizationValue.fnumber"
          other-height="68vh"
          :other-url-object="otherUrlObject"
        />
      </el-tab-pane>
    </el-tabs>
    <!--    物料弹窗-->
    <el-dialog
      v-dialogDrag
      :title="$t('menu.materielList')"
      model
      :visible.sync="isMaterielDialog"
      :close-on-click-modal="false"
      width="60%"
      destroy-on-close
      @close="closeNum"
    >
      <div class="materiel-form">
        <search :options="selectData" :msg="tacitly" @seek="collect" @hand="handleMaterielSearch" />
        <el-button size="mini" type="primary" class="btn" @click="handleMaterielSearch">{{ $t('btn.search') }}</el-button>
      </div>
      <jc-table
        :table-data="materielDialogData"
        :table-header="materielDialogHeader"
        table-height="53vh"
        serial
        @clickRow="materielSelectRow"
      />
      <jc-pagination
        v-show="materielPagination.total > 0"
        :total="materielPagination.total"
        :page.sync="materielPagination.pageNum"
        :limit.sync="materielPagination.pageSize"
        @pagination="handleGetMateriel"
      />
    </el-dialog>
    <!--    币别列表弹窗-->
    <currency v-if="currencyVisiblit" @currency="currencyData" />
    <!--客户列表-->
    <client v-if="clientVisiblit" :msg="organizationValue.fsaleOrgId" @client="clientData" />
  </div>
</template>

<script>

import {
  querySalPriceNtry,
  updateSalPrice,
  salPriceListSubmit,
  reviewPrice,
  notReviewPrice,
  againReviewPrice, deleteSalPrice, salPriceListDisable, salPriceListUnDisable
} from '@/api/marketManage/marketPriceList'
import {
  queryMaterialList
} from '@/api/marketManage/marketOrder'
import jumpMateriel from '@/components/JumpMateriel' // 物料详情
import jcMarker from '@/components/marker'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import operability from '@/mixin/Operability'
import jcButton from '@/components/Button'

export default {
  components: {
    jcMarker,
    currency: () => import('@/views/market/marketManage/createMarkerOrder/components/currency'),
    client: () => import('@/views/market/marketManage/createMarkerOrder/components/client'),
    search,
    numberCode: () => import('@/components/NumberCode'),
    jcButton
  },
  mixins: [jumpMateriel, searData, autocomplete, operability],

  data() {
    return {
      val: [],
      ftype: 0,
      fbillNo: 'fnumber', // 编码
      targerName: 'marked', // 销售价目
      rate: 1.13, // 销售基准价(默认13%税率)
      fdownPriceRate: '13', // 销售基准价税率
      isMaterielDialog: false, // 物料弹窗
      isDisabled: false,
      fnumber: '',
      aotuTab: false,
      // 物料弹窗分页
      materielPagination: {
        total: 0, // 总条目
        pageNum: 1, // 当前页
        pageSize: 20 // 每页显示多少条数据
      },
      FNUMBER: '', // 弹窗编码
      FDESCRIPTION: '', // 弹窗描述
      FSPECIFICATION: '', // 弹窗规格型号
      materielDialogData: [],
      materielDialogHeader: [
        { label: this.$t('market.fmaterial'), prop: 'fnumber', minWidth: '150px' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion', minWidth: '150px' },
        { label: this.$t('market.fmodel'), prop: 'fmodel', minWidth: '100px' },
        { label: this.$t('market.descrip'), prop: 'fdescripTion', minWidth: '300px' },
        { label: this.$t('market.createDate'), prop: 'fcreateDate', minWidth: '120px' }
      ],
      // 点击行的序号
      tableIndex: 0,
      // 表头
      tableData: [], // 价目明细数据
      tableHeader: [],
      tableHeight: '70vh',
      // 表单
      organizationValue: {}, // 表单组织值
      organization: {}, // 表单组织控件
      limitName: '客户',
      // 结算币别
      currencyVisiblit: false,
      clientVisiblit: false, // 客户列表
      otherUrlObject: {}, // 其它审核人
      pageNum: 1,
      size: 200,
      total: 0
    }
  },
  created() {
    this.queryTSalOrderNtry()
    // this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 280px)' : '61vh'
  },
  methods: {
    // 输入物料编码
    getAtuo(index, fnumber) {
      this.tableIndex = index
      this.aotuTab = true
      var vm = this
      clearTimeout(vm.timer) // 清除未执行的代码，重置回初始化状态
      vm.timer = setTimeout(() => {
        this.fnumber = fnumber
      }, 600)
    },
    // 获取订单列表数据
    async queryTSalOrderNtry() {
      const id = this.$route.params.id
      const DATA = { fid: id }
      const { data: RES } = await querySalPriceNtry(DATA)
      this.tableData = RES.detail
      this.organizationValue = RES
      this.isDisabled = this.organizationValue.fdocumentStatus === this.$t('market.state1') || this.organizationValue.fdocumentStatus === this.$t('market.state2')
      this.otherUrlObject = RES
    },
    closeNum() {
      this.isMaterielDialog = false
      this.materielPagination.pageNum = 1
      this.materielPagination.pageSize = 10
      Object.keys(this.searCollData).forEach(key => {
        this.searCollData[key] = ''
      })
    },
    // 保存
    subMarker(ev) {
      for (const item of this.tableData) {
        if (!item.fnumber) {
          this.$message.error('表格不能为空或删除空行')
          return false
        }
      }
      const DATA = this.organizationValue
      this.organizationValue.fdocumentStatus = ev
      this.organizationValue.priceDetails = this.tableData
      updateSalPrice(DATA).then(res => {
        if (res.code === 0) {
          // 提交先保存
          if (ev === 'B') {
            this.subPrice()
          } else {
            this.queryTSalOrderNtry()
            this.$message({ type: 'success', message: '修改成功' })
          }
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 提交
    subPrice() {
      const api = salPriceListSubmit
      this.toExamineFun(api)
    },
    // 监听价格
    priceHandel(price, index) {
      const item = this.tableData[index]
      item.fdownPrice = price
    },
    // 物料弹窗选中
    async materielSelectRow(item, index) {
      const items = this.tableData[this.tableIndex]
      items.fmaterialId = item.fmaterialId
      items.funitId = item.funitId
      items.fnumber = item.fnumber
      items.funit = item.funitName
      items.fmodel = item.fmodel
      items.fspecificaTion = item.fspecificaTion
      items.fdescripTion = item.fdescripTion
      this.isMaterielDialog = false
      this.aotuTab = true
    },
    // 打开物料编码
    async handleGetMateriel(row, index) {
      if (index || index === 0) {
        this.index = index
        this.tableIndex = index
      }
      const DATA = {
        pageNum: this.materielPagination.pageNum,
        pageSize: this.materielPagination.pageSize,
        search: this.searCollData
      }
      const { data: RES } = await queryMaterialList(DATA)
      this.materielDialogData = RES.array
      this.materielPagination.total = RES.total
      this.isMaterielDialog = true
    },
    // 物料搜索
    handleMaterielSearch() {
      this.materielPagination.pageNum = 1
      this.handleGetMateriel()
    },
    // 选择币别
    currencyData(item) {
      if (item.fsettleCurrId || item.fcurrencyId) {
        this.organizationValue.fcurrency = item.fsettleCurrIdName || item.fname
        this.organizationValue.fcurrencyId = item.fsettleCurrId || item.fcurrencyId
        this.currencyVisiblit = false
      } else {
        // 点击关闭按钮
        this.currencyVisiblit = false
      }
    },
    // 获取客户数据(子传父)
    clientData(item) {
      this.organizationValue.fcustId = item.fcustId
      this.organizationValue.fcustName = item.fname
      this.clientVisiblit = false
    },
    // 删除明细空行
    delectSale(index) {
      this.tableData.splice(index, 1)
    },
    // 监听销售系数
    inputNum(index) {
      this.tableIndex = index
      if (this.tableData[this.tableIndex].fmaterialId) {
        const tBase = (this.tableData[this.tableIndex].fpriceBase) / 100
        const tPrice = this.tableData[this.tableIndex].deliveryPrice
        this.tableData[this.tableIndex].fdownPrice = (tPrice * (1 + tBase)) // 基准价
      }
    },
    // 新增行
    newHang() {
      this.tableData.push(
        {
          fmaterialId: '', // 物料编码ID
          fentryId: 0,
          fnumber: '', // 物料编码
          funit: '', // 单位
          funitId: '', // 单位id
          fpriceBase: 1, // 销售系数
          fprice: '', // 出厂价
          fdownPrice: '', // 最低限价
          fexpriydate: '2100-01-01', // 失效期
          feffectivedate: new Date() // 生效期
        }
      )
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: [this.organizationValue.fnumber] }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.queryTSalOrderNtry()
        this.selectFbi = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 审核
    audit(ev) {
      const api = ev === 1 ? reviewPrice : notReviewPrice
      this.toExamineFun(api)
    },
    // 禁用 反禁用
    forbidden(ev) {
      const api = ev === 1 ? salPriceListDisable : salPriceListUnDisable
      this.toExamineFun(api)
    },
    // 反提交
    againReviewPrice() {
      const api = againReviewPrice
      this.toExamineFun(api)
    },
    // 删除销售价目
    delectHandle() {
      if (this.isDisabled) {
        this.$confirm('请先反审核后再删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      const DATA = { Numbers: [this.organizationValue.fnumber] }
      this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSalPrice(DATA).then((res) => {
          if (res.code === 0) {
            // 关闭当前页面
            this.$store.dispatch('tagsView/guanbi', this.$route)
            this.$router.push({ path: '/marketPriceList' })
            this.$message({ showClose: true, message: res.message, type: 'success' })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      })
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 删除行
    delHang() {
      this.tableData.splice(this.indexSelf, 1)
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      this.property = column.property
      this.subscript = row.index
    },
    // 批量填充
    batchFill() {
      const item = this.tableData[this.subscript][this.property]
      this.tableData.map((res, index) => {
        if (index >= this.subscript) {
          res[this.property] = item
        }
      })
    },
    handleOther(tab) {
      if (tab.name === 'log') {
        this.$refs.log.otherlog()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.markedEdit {
  @include listBom;
  .table-content {
    margin-bottom: 5px;
  }
  .tabPosit {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: 4.8vh;
    left: 0vw;
    background-color: rgba(255, 255, 255, 1);
    z-index: 99999!important;
  }
  .tabPosit1 {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: -25.69vh;
    left:0vw;
    background-color: rgba(255, 255, 255, 1);
    z-index: 9999;
  }
  .el-table {
    margin-top: 8px;
    &::v-deep td{
      padding: 8px 0;
    }
    &::v-deep thead.is-group th{
      padding: 3px 0;
      .el-input__inner{
        background: #e6ebfc;
        color: #909399;
        font-size: 13px;
        font-weight: 550;
        border: none;
      }
    }
  }
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-form{
    display: flex;
    flex-wrap: wrap;
    .el-form-item {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 275px;
      margin-bottom: 0;
    }
  }
}
.materiel-form{
  position:relative;
  width: 100%;
  bottom: 5px;
  .btn{
    transform: translateY(18%);
    margin-left: 450px !important;
    z-index: 999;
  }
  .btn1 {
    margin-left: 15px !important;
  }
}
.materiel-form {
  display: flex;
  align-items: center;
  flex-direction: row;

  .materiel-code {
    margin-right: 5px;
    font-weight: bold;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    min-width: 65px;
  }

  .input-width {
    width: 200px;
    margin-right: 10px;
  }
}
.el-table{
  &::v-deep .el-input-number .el-input__inner{
    padding: 0;
    width: 80px;
  }
  &::v-deep .el-input-number .el-input{
    width: 80px;
  }
  &::v-deep .el-input-number--mini {
    width: 80px;
  }
  &::v-deep .el-input-number__increase{
    display: none;
  }
  &::v-deep .el-input-number__decrease{
    display: none;
  }
  &::v-deep .el-table__footer-wrapper tbody td{
    font-size: 12px;
    background: #fdf6ec!important;
  }
}
</style>
